﻿using System;
using System.Linq.Expressions;
using System.Reflection;
using DNT.RavenQA.Core.Extensions;

namespace DNT.RavenQA.Web.Infrastructure.Extensions
{
    public static class Name
    {
        public static String Of(LambdaExpression selector)
        {
            selector.EnsureIsNotNull("selector");

            var mexp = selector.Body as MemberExpression;

            if (mexp.IsNull())
            {
                var uexp = (selector.Body as UnaryExpression);

                if (uexp.IsNull())
                    throw new TargetException("Cannot determine the name of a member using an expression because the expression provided cannot be converted to a '" +
                                              typeof(UnaryExpression).Name + "'.");

                mexp = uexp.Operand as MemberExpression;
            }

            if (mexp.IsNull())
                throw new TargetException("Cannot determine the name of a member using an expression because the expression provided cannot be converted to a '" +
                                          typeof(MemberExpression).Name + "'.");

            return mexp.Member.Name;
        }

        public static String Of<TSource>(Expression<Func<TSource, Object>> selector)
        {
            return Of<TSource, Object>(selector);
        }

        public static String Of<TSource, TResult>(Expression<Func<TSource, TResult>> selector)
        {
            return Of(selector as LambdaExpression);
        }
    }
}